//
//  AddCardViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/25.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "AddCardViewController.h"
#import "BankListViewController.h"

@interface AddCardViewController ()<selectBankDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSInteger count;
    NSMutableArray *array;
    UIImagePickerController *imagepc;
}
@property (weak, nonatomic) IBOutlet UITextField *textName;
@property (weak, nonatomic) IBOutlet UITextField *idcard;
@property (weak, nonatomic) IBOutlet UITextField *bankcard;
@property (weak, nonatomic) IBOutlet UITextField *textPhone;
@property (weak, nonatomic) IBOutlet UITextField *textCode;

@property (weak, nonatomic) IBOutlet UIImageView *image1;
@property (weak, nonatomic) IBOutlet UIImageView *image2;


@property (weak, nonatomic) IBOutlet UIButton *btnCode;
@property (weak, nonatomic) IBOutlet UIButton *selecrBack;
@property (nonatomic, strong) NSString *backId;

- (IBAction)selectEvent:(UIButton *)sender;

@property (nonatomic,copy)NSString *state;

@property (nonatomic,copy)NSString *imgUrl1;
@property (nonatomic,copy)NSString *imgUrl2;


@end

@implementation AddCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self showNav:@"添加银行卡"];
    array = [NSMutableArray array];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click1)];
    _image1.userInteractionEnabled = YES;
    [_image1 addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2)];
    _image2.userInteractionEnabled = YES;
    [_image2 addGestureRecognizer:tap2];
    
}

- (void)click1{
    _state = @"aaa";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从手机相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
    
}
#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    if ([_state isEqualToString:@"aaa"]) {
        _image1.image = img;
    }else{
        _image2.image = img;
    }
    
    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
- (void)loadImage:(UIImage *)image{
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    if ([_state isEqualToString:@"aaa"]) {//正面
        [parmas setObject:@"justimg" forKey:@"identification"];
    }else{
        [parmas setObject:@"backimg" forKey:@"identification"];
    }
    
    [parmas setObject:@"idcardnoimg.png" forKey:@"idcardnoimg"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/editIdcardimg",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"idcardnoimg" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSString *status = [op objectForKey:@"status"];
        NSLog(@"dic:%@",op);
        if ([status integerValue] == 200) {
            if ([_state isEqualToString:@"aaa"]) {
                _imgUrl1 = [op objectForKey:@"content"];
            }else{
                _imgUrl2 = [op objectForKey:@"content"];
            }
        }
        [LICGToast showWithText:[op objectForKey:@"msg"]];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)click2{
    _state = @"sss";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从手机相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBAction)clickCode:(id)sender {
    if ([_textPhone.text isEqualToString:@""]) {

        [LICGToast showWithText:@"手机号不能为空"];
    }else if ([self validateMobile:_textPhone.text] == 0){
        [LICGToast showWithText:@"手机号格式不正确"];
    }else{
        [self performSelector:@selector(countClick) withObject:nil];
        _btnCode.enabled = NO;
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setObject:_textPhone.text forKey:@"mobile"];
        [parmas setObject:@"5" forKey:@"k"];
        NSLog(@"parmas:%@",parmas);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/CallSms",urlHead];
        [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"res:%@",responseObject);
            NSString *str = [responseObject objectForKey:@"status"];
            if ([str integerValue] != 200) {
                _btnCode.enabled = YES;
            }
            [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
        }];
        
    }
    
}
//
-(void)countClick
{
    _btnCode.enabled = NO;
    count = 119;
    [_btnCode setTitle:@"119秒后重新获取" forState:UIControlStateNormal];
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
}

- (void)timerFired:(NSTimer *)time{
    if (count !=1) {
        count -=1;
        
        NSString *str = [NSString stringWithFormat:@"%li",count];
        NSString *str2 = @"秒后重新获取";
        NSString *title = [NSString stringWithFormat:@"%@%@",str,str2];
        
        [_btnCode setTitle:title forState:UIControlStateNormal];
    }else{
        [time invalidate];//关闭定时器
        _btnCode.enabled = YES;
        [_btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    
}
//添加银行卡
- (IBAction)clickAdd:(id)sender {
    NSLog(@"imgurl1:%@",_imgUrl1);
    NSLog(@"imgurl2:%@",_imgUrl2);
    if (_textName.text.length == 0) {
        [LICGToast showWithText:@"请输入姓名"];
        return;
    }else if (_idcard.text.length == 0){
        [LICGToast showWithText:@"请输入身份证号"];
        return;
    }else if ([self checkIdentityCardNo:_idcard.text] == 0){
        [LICGToast showWithText:@"身份证号格式不正确"];
        return;
    }else if (_imgUrl1.length == 0){
        [LICGToast showWithText:@"请上传身份证正面照"];
        return;
    }else if (_imgUrl2.length == 0){
        [LICGToast showWithText:@"请上传身份证反面照"];
        return;
    }else if (_bankcard.text.length == 0){
        [LICGToast showWithText:@"请输入银行卡号"];
        return;
    }else if (_textPhone.text.length == 0){
        [LICGToast showWithText:@"请输入手机号"];
        return;
    }else if ([self validateMobile:_textPhone.text] == 0){
        [LICGToast showWithText:@"手机号格式不正确"];
        return;
    }else if (_textCode.text.length == 0){
        [LICGToast showWithText:@"请输入验证码"];
        return;
    }else if (_backId.length == 0){
        [LICGToast showWithText:@"请选择银行"];
        return;
    }
    
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    //621226 31000 4333 1912
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setObject:_textName.text forKey:@"username"];
    [parmas setObject:_bankcard.text forKey:@"banknumber"];
    [parmas setObject:_textPhone.text forKey:@"rephone"];
    [parmas setObject:_textCode.text forKey:@"smscode"];
    [parmas setObject:_idcard.text forKey:@"id"];
    [parmas setValue:self.backId forKey:@"bankid"];
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/addBankCard",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"添加银行卡res:%@",responseObject);
        NSString *state = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        NSString *msg = [responseObject objectForKey:@"msg"];
        if ([state integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        [LICGToast showWithText:msg];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)selectEvent:(UIButton *)sender {
    BankListViewController *list = [[BankListViewController alloc]init];
    list.delegate = self;
    [self.navigationController pushViewController:list animated:YES];
}

#pragma mark =====selectBankDelegate

- (void)selectBankAction:(NSDictionary *)dic{
    self.backId = [dic objectForKey:@"id"];
    [self.selecrBack setTitle:[dic objectForKey:@"bankname"] forState:UIControlStateNormal];
}

@end
